import { createApp } from 'vue';
import App from './App.vue';

//引入UI组件
import * as Vant from 'vant';

//引入组件样式
import 'vant/lib/index.css';

//引入请求服务
import Request from './services/request';

//引入自定义函数
import Tools from './tools/tools';

//引入状态管理
import { createPinia } from 'pinia';

//引入状态持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

//引入cookie插件
import Cookies from 'vue3-cookies';

//引入路由
import Router from './router/index';

const app = createApp(App)
    .use(Vant)
    .use(Router)
    .use(Request)
    .use(createPinia().use(piniaPluginPersistedstate))
    .use(Tools)
    .use(Cookies)
    .mount('#app')

// 前置路由守卫
app.$router.beforeEach(async (to, from) => {
    // to: 要跳转的路由，from: 从哪里跳转
    // 获取跳转路由的自定义属性
    const IsLogin = to.meta.IsLogin === true ? true : false;

    // 登录属性等于true，走验证登录
    if (IsLogin === true) {
        // 获取登录信息
        const business = app.$business;

        if (!business || Object.getOwnPropertyNames(business.value).length === 0) {
            app.$fail('请先登录');

            // 重定向到登录页面
            return { path: '/login' };
        }

        const id = business.value.id ?? 0;

        const result = await app.$http.post({
            url: '/user/check',
            params: {
                id,
            }
        });

        if (result.code === 1) {
            // 更新登录信息
            app.$business.value = result.data;

            // 往下走 放行
            return true;
        } else {
            app.$fail(result.msg);

            return { path: '/login' };
        }
    } else {
        const id = app.$business.value.id ?? 0;

        if (id === 0) {
            return;
        }

        const result = await app.$http.post({
            url: '/user/check',
            params: {
                id
            }
        });

        if (result.code === 1) {
            // 更新登录信息
            app.$business.value = result.data;

            // 往下走 放行
            return true;
        }
    }
})

